package com.abbas.CayTcore.presenter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.abbas.CayTcore.R
import com.abbas.CayTcore.base.BasePresenter
import com.abbas.CayTcore.entity.LW
import com.abbas.CayTcore.entity.TCoreBase
import com.abbas.CayTcore.model.WindingAllDataUpModel
import com.abbas.CayTcore.ui.CoreDetailFragment
import com.abbas.CayTcore.view.ViewContract
import q.rorbin.verticaltablayout.adapter.TabAdapter
import q.rorbin.verticaltablayout.widget.ITabView

class WindingAllDataUpPresenter :
    BasePresenter<ViewContract.WindingAllDataUpView, WindingAllDataUpModel>() {

    var coreList: List<TCoreBase> = emptyList()

    override fun initModel(): WindingAllDataUpModel {
        return WindingAllDataUpModel()
    }

    fun getAllCore(){
        model.getAllCore {
            coreList = it
            val groupBy = it.groupBy { core ->
                core.getLW()
            }.keys.toList()
            coreLWSorted(groupBy)
        }
    }

    fun groupCore(lw: LW){
        val filter = coreList.filter {
            it.length == lw.l && it.width == lw.w
        }
        if (filter.isNotEmpty()) {
            view.get()?.coreLwTypeFilter(object : TabAdapter {
                override fun getCount(): Int = filter.size

                override fun getBadge(position: Int): ITabView.TabBadge =
                    ITabView.TabBadge.Builder()
                        .setBackgroundColor(R.color.gray200)
                        .build()

                override fun getIcon(position: Int): ITabView.TabIcon? = null

                override fun getTitle(position: Int): ITabView.TabTitle =
                    ITabView.TabTitle.Builder()
                        .setContent(filter[position].getHG())
                        .setTextColor(R.color.colorPrimary, R.color.gray200)
                        .build()

                override fun getBackground(position: Int): Int {
                    return when (position % 2) {
                        0 -> R.color.gray200
                        else -> android.R.color.white
                    }
                }
            },object : FragmentStatePagerAdapter((view.get() as Fragment).childFragmentManager,
                BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            ) {
                override fun getCount(): Int = filter.size

                override fun getItem(position: Int): Fragment =
                    CoreDetailFragment(filter[position])

                override fun getPageTitle(position: Int): CharSequence? {
                    return filter[position].getHG()
                }
            })
        }else{
            view.get()?.showToast("未查询到对应磁芯数据")
        }
    }

    private fun coreLWSorted(sortedData: List<String>){
        if (sortedData.isNotEmpty()){
            view.get()?.onCoreLWGet(sortedData)
        }else{
            view.get()?.showToast("未查询到磁芯数据")
        }
    }

}